<?php


namespace common\helpers;

use DfaFilter\SensitiveHelper;
use yii\base\UserException;
use yii\helpers\ArrayHelper;

class BaseHelper
{
    /**
     * 无效参数异常
     *
     * @param int $code
     * @param string $message
     *
     * @throws UserException
     */
    public static function invalidException($code, $message)
    {
        if (is_array($message)) {
            $message = json_encode($message);
        }
        throw new UserException($message, $code);
    }

    /**
     * 是否序列化
     *
     * @param string $string
     *
     * @return bool
     */
    public static function isJson($string)
    {
        if (is_array($string)) {
            return $string;
        }
        $data = json_decode($string, true);
        return (json_last_error() == JSON_ERROR_NONE) ? $data : $string;
    }

    /**
     * 数组json格式化
     *
     * @param array $params
     * @param bool $isKey id 是否为key
     *
     * @return array
     * @author lengbin(lengbin0@gmail.com)
     */
    public static function formattingDataForJson(array $params, $isKey = true)
    {
        $data = [];
        foreach ($params as $id => $text) {
            $data[] = [
                'id' => $isKey ? $id : $text,
                'name' => $text,
            ];
        }
        return $data;
    }

    /**
     * unset
     *
     * @param array $data
     * @param array $fields
     *
     * @return mixed
     */
    public static function formattingUnset(array $data, array $fields)
    {
        foreach ($fields as $key => $field) {
            if (!is_int($key) && isset($data[$key])) {
                $data[$field] = $data[$key];
                $field = $key;
            }
            if (isset($data[$field])) {
                unset($data[$field]);
            }

        }
        return $data;
    }

    /**
     * 数组json格式化
     *
     * @param array $params
     *
     * @return array
     * @author lengbin(lengbin0@gmail.com)
     */
    public static function formattingModelForJson(array $params, $fields = ['id', 'name'])
    {
        $data = [];
        foreach ($params as $param) {
            $d = [];
            foreach ($fields as $key => $field) {
                if (is_int($key)) {
                    $key = $field;
                }
                $d[$key] = $param[$field];
            }
            $data[] = $d;
        }
        return $data;
    }

    /**
     * 时间格式化
     *
     * @param string /int  $date  时间/时间戳
     * @param bool $isInt 是否为int
     *
     * @return array
     * @author lengbin(lengbin0@gmail.com)
     */
    public static function formattingDay($date, $isInt = true)
    {
        return self::formattingDays($date, $date, $isInt);
    }

    /**
     * 双日期 格式化
     *
     * @param string $date 双日期
     * @param string $separatrix 分割符
     * @param bool $isInt 是否为int
     *
     * @return array
     */
    public static function formattingDoubleDate($date, $separatrix = ' - ', $isInt = true)
    {
        $dates = explode($separatrix, $date);
        return self::formattingDays($dates[0], $dates[1], $isInt);
    }

    /**
     * 时间格式化
     *
     * @param string /int  $start  时间/时间戳
     * @param string /int  $end  时间/时间戳
     * @param bool $isInt 是否为int
     *
     * @return array
     * @author lengbin(lengbin0@gmail.com)
     */
    public static function formattingDays($start, $end, $isInt = true)
    {
        if (is_int($start)) {
            $start = date('Y-m-d', $start);
        }
        if (is_int($end)) {
            $end = date('Y-m-d', $end);
        }
        $start = $start . ' 00:00:00';
        $end = $end . ' 23:59:59';
        if ($isInt) {
            $start = strtotime($start);
            $end = strtotime($end);
        }
        return [$start, $end];
    }

    /**
     * 时间格式化
     *
     * @param int $month 月份
     * @param bool $isInt 是否为int
     *
     * @return array
     * @author lengbin(lengbin0@gmail.com)
     */
    public static function formattingMonth($month, $isInt = true)
    {
        if (strlen($month) < 3) {
            $month = date("Y-{$month}-d");
        }
        $timestamp = strtotime($month);
        $startTime = date('Y-m-1 00:00:00', $timestamp);
        $mdays = date('t', $timestamp);
        $endTime = date('Y-m-' . $mdays . ' 23:59:59', $timestamp);
        if ($isInt) {
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
        }
        return [$startTime, $endTime];
    }

    /**
     * 获得 image url
     * @return mixed|null|string
     */
    public static function getImageUrl()
    {
        $imageUrl = ArrayHelper::getValue(\Yii::$app->params, 'imageUrl');
        if (empty($imageUrl)) {
            $imageUrl = \Yii::$app->request->hostInfo;
        }
        return $imageUrl;
    }

    /**
     * 正则
     *
     * @param string $url
     *
     * @return int
     * @author lengbin(lengbin0@gmail.com)
     */
    public static function checkUrl($url)
    {
        $rule = "/((http|https):\/\/)+(\w+\.)+(\w+)[\w\/\.\-]*/";
        preg_match($rule, $url, $result);
        return $result;
    }

    /**
     * 图片地址
     *
     * @param string $path
     *
     * @return mixed|null|string
     */
    public static function imageUrl($path)
    {
        return self::checkUrl($path) ? $path : self::getImageUrl() . $path;
    }

    /**
     *  根据两点间的经纬度计算距离
     *
     * @param float $lat 纬度值
     * @param float $lng 经度值
     *
     * @return float
     */
    public static function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000;
        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;
        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }

    /**
     * 人性化时间显示
     *
     * @param int $time
     *
     * @return false|string
     */
    public static function formatTime($time)
    {
        $rtime = date("Y-m-d H:i:s", $time);
        $time = time() - $time;
        if ($time < 60) {
            $str = '刚刚';
        } elseif ($time < 60 * 60) {
            $min = floor($time / 60);
            $str = $min . '分钟前';
        } elseif ($time < 60 * 60 * 24) {
            $h = floor($time / (60 * 60));
            $str = $h . '小时前 ';
        } elseif ($time < 60 * 60 * 24 * 3) {
            $d = floor($time / (60 * 60 * 24));
            if ($d == 1) {
                $str = '昨天 ' . $rtime;
            } else {
                $str = '前天 ' . $rtime;
            }
        } else {
            $str = $rtime;
        }
        return $str;
    }


    /**
     * 敏感词过滤
     *
     * @param $content
     *
     * @return string
     * @throws \Exception
     */
    public static function filterWorld($content)
    {
        if (empty($content)) {
            return $content;
        }
        $path = \Yii::getAlias('@common') . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'dict.txt';
        return SensitiveHelper::init()->setTreeByFile($path)->replace($content, '**');
    }

    /**
     * 下划线转驼峰
     * 思路:
     * step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
     * step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
     */
    public static function camelize($uncamelized_words, $separator = '_')
    {
        $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
        return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
    }

    /**
     * 驼峰命名转下划线命名
     * 思路:
     * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
     */
    public static function uncamelize($camelCaps, $separator = '_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }

    /**
     * 是否 手机浏览器访问
     * @return bool
     */
    public static function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
            return true;

        //此条摘自TPM智能切换模板引擎，适合TPM开发
        if (isset ($_SERVER['HTTP_CLIENT'])
            && 'PhoneClient' == $_SERVER['HTTP_CLIENT'])
            return true;
        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
            //找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'],
                'wap') ? true : false;
        //判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array(
                'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile'
            );
            //从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/("
                . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        //协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'],
                        'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'],
                        'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'],
                            'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'],
                            'text/html')))) {
                return true;
            }
        }
        return false;
    }

    public static function getUrl($url)
    {
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }

    public static function curlGet($url)
    {

        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        //curl_close($curl);

        // 显示错误信息
        if (curl_error($curl)) {
            return [curl_error($curl)];
        } else {
            return json_decode($data, true);
        }
    }

}
